<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { Ref } from 'vue'
import {
  updateNoteServer,
  deleteNoteServer,
  addNoteServer,
  getNoteServer
} from '@/api/server/note'
import {
  getLoginUserSpacesServer,
  updateSpaceServer,
  addSpaceServer,
  deleteSpaceServer,
  getSpaceTreeServer
} from '@/api/server/space'
import { formatDate } from '@/utils/formatDate'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
//获取笔记内容
// 获取一篇笔记/一个空间数据
const note: Ref<any> = ref({
  id: null,
  noteId: null,
  spaceId: null,
  title: null,
  content: null,
  noteSize: null,
  type: 'note',
  createTime: null,
  updateTime: null
})
const space: Ref<any> = ref({
  id: null,
  spaceName: null,
  spaceDesc: null,
  spaceCount: null,
  noteCount: null,
  noteList: null,
  parentId: null,
  noteSize: null,
  type: 'space'
})
const tree: Ref<Array<any>> = ref([])
const getTree = async (spaceId: any) => {
  const res = await getSpaceTreeServer(spaceId)
  tree.value = res.data
  // 1.把从后端获取的元素的属性 spaceName|title 修改为label
  // 2.把元素的noteList 加入到children
  // 3.把每个元素的id修改为key
  // 4.计算每个元素的笔记和空间数量

  const processNode = (node: any) => {
    let noteCount = node.noteList?.length || 0
    let spaceCount = 0
    // 1. 将属性 spaceName 或 title 复制 label
    node.label = node.spaceName || node.title
    node.key = node.id
    // 2. 将元素的 noteList 加入到 children 中
    if (node.noteList && node.noteList.length > 0) {
      if (!node.children) {
        node.children = []
      }
      node.noteList.forEach((note: any) => {
        node.children.unshift(note)
      })
    }
    // 3. 递归处理子节点
    if (node.children && node.children.length > 0) {
      node.children.forEach((child: any) => {
        // 递归处理子节点，并累加其返回的笔记数目和空间数目
        const { noteCount: childNoteCount, spaceCount: childSpaceCount } =
          processNode(child)
        noteCount += childNoteCount
        spaceCount += childSpaceCount
      })
      spaceCount = spaceCount + node.children.length - node.noteList.length
    }
    // 更新节点的笔记数目和空间数目属性
    node.noteCount = noteCount
    node.spaceCount = spaceCount

    // 返回当前节点的笔记数目和空间数目
    return { noteCount, spaceCount }
  }

  //4. 遍历树中的每个节点，调用递归函数处理节点
  if (!tree.value) return
  tree.value.forEach((item) => {
    processNode(item)
  })
  //5. 根据传入父空间Id重构摘取tree
  tree.value = tree.value.filter((item) => item.id === route.query.spaceId)
}
//树配置
const defaultProps = {
  children: 'children',
  label: 'id'
}
//获取空间/笔记
const getData = async () => {
  if (route.query.noteId) {
    const res = await getNoteServer(route.query.noteId)
    note.value = res?.data
  }
  if (route.query.spaceId) {
    await getTree(route.query.spaceId)
    space.value = { ...tree.value[0] }
    space.value.spaceCount = route.query.spaceCount
    space.value.noteCount = route.query.noteCount
  }
}
//笔记重命名
const isRenameNote: Ref<boolean> = ref(false)
//更新笔记
const updateNote = async () => {
  await updateNoteServer(note.value)
}
//空间简介编辑/重命名
const isSpaceEdit: Ref<boolean> = ref(false)
//更新简介/名字
const updateSpace = async () => {
  await updateSpaceServer(space.value)
}
onMounted(async () => {
  await getData()
})
</script>

<template>
  <div class="content">
    <n-layout-content>
      <div class="note-content" v-if="route.query.noteId">
        <el-card>
          <template #header>
            <el-row align="middle">
              <el-col :span="4">
                <el-input
                  v-model="note.title"
                  v-if="isRenameNote"
                  :maxlength="45"
                  show-word-limit
                  @keyup.enter="
                    () => {
                      updateNote()
                      isRenameNote = !isRenameNote
                    }
                  "
                ></el-input>
                <div class="note-info" v-else>
                  <el-text type="primary" size="large"
                    >笔记名: {{ note.title }}</el-text
                  >
                  <el-divider direction="vertical" />
                  <el-text type="success" size="small">
                    大小: {{ note.noteSize }}
                  </el-text>
                </div>
              </el-col>
              <el-col :span="16">
                <el-popover trigger:hover :show-after="500" placement="top">
                  <template #reference>
                    <el-button size="small" type="success" plain round>
                      <el-icon @click="updateNote"><Upload /></el-icon>
                    </el-button>
                  </template>
                  <template #default>更新</template>
                </el-popover>
                <el-divider direction="vertical"></el-divider>
                <el-text>上次更新: {{ note.updateTime }}</el-text>
              </el-col>
              <el-col :span="4">
                <el-button
                  plain
                  round
                  type="primary"
                  @click="isRenameNote = !isRenameNote"
                  v-if="!isRenameNote"
                  >重命名</el-button
                >
                <el-button
                  plain
                  round
                  type="primary"
                  @click="
                    async () => {
                      isRenameNote = !isRenameNote
                      await getData()
                    }
                  "
                  v-else
                  >取消</el-button
                >
              </el-col>
            </el-row>
          </template>
          <template #default>
            <editor v-model="note.content" :key="note.content"> </editor>
          </template>
        </el-card>
      </div>
      <div class="space-content" v-if="route.query.spaceId">
        <el-card shadow="never">
          <template #header>
            <el-row justify="space-between">
              <el-col :span="6">
                <el-input
                  v-model="space.spaceName"
                  :maxlength="45"
                  show-word-limit
                  @keyup.enter="
                    () => {
                      updateSpace()
                      isSpaceEdit = !isSpaceEdit
                    }
                  "
                  v-if="isSpaceEdit"
                ></el-input>
                <el-text
                  size="large"
                  type="success"
                  @click="isSpaceEdit = !isSpaceEdit"
                  v-else
                >
                  {{ space.spaceName }}
                </el-text>
              </el-col>
              <el-col :span="6">中间部分，可以不写东西的 </el-col>
              <el-col :span="6">
                <el-button
                  @click="isSpaceEdit = !isSpaceEdit"
                  v-if="!isSpaceEdit"
                  >编辑</el-button
                >
                <el-button v-else @click="isSpaceEdit = !isSpaceEdit"
                  >取消</el-button
                >
                <el-divider direction="vertical"></el-divider>
                <el-popover placement="top-start" trigger="hover">
                  <el-text size="small">enter保存</el-text>
                  <template #reference>
                    <el-icon><Warning /></el-icon>
                  </template>
                </el-popover>
              </el-col>
            </el-row>
            <el-row justify="space-between">
              <el-col :span="6">
                <el-text size="small" type="primary">
                  <el-space>
                    <el-text> 笔记数: {{ space.noteCount }}</el-text>
                    <el-text> 空间数: {{ space.spaceCount }}</el-text>
                    <el-text> 总大小: {{ space.spaceSize }}</el-text>
                    <el-popover placement="top-start" trigger="hover">
                      <el-text size="small"> (8,16,24)时统计</el-text>
                      <template #reference>
                        <el-icon><Warning /></el-icon>
                      </template>
                    </el-popover>
                  </el-space>
                </el-text>
              </el-col>
            </el-row>
          </template>
          <template #default>
            <div class="desc">
              <el-text v-if="!isSpaceEdit"
                >空间简介：{{ space.spaceDesc }}
              </el-text>

              <el-input
                v-else
                type="textarea"
                placeholder="输入简介"
                v-model="space.spaceDesc"
                maxlength="250"
                show-word-limit
                @keyup.enter="
                  () => {
                    updateSpace()
                    isSpaceEdit = !isSpaceEdit
                  }
                "
              ></el-input>
            </div>
            <el-tree
              :data="tree"
              :props="defaultProps"
              :default-expand-all="true"
              :expand-on-click-node="false"
            >
              <template #default="{ data }">
                <n-flex
                  class="node"
                  justify="space-between"
                  style="width: 100%"
                >
                  <el-text type="primary">{{ data.label }}</el-text>
                  <span class="line"></span>
                  <el-text type="primary"
                    >{{ formatDate(data.updateTime) }}
                  </el-text>
                </n-flex>
              </template>
            </el-tree>
          </template>
        </el-card>
      </div>
    </n-layout-content>
  </div>
</template>

<style scoped lang="scss">
.content {
  margin: 0;
  $head-height: 60px;
  $footer-height: 50px;
  $main-height: calc(100vh - $head-height - $footer-height);
  .note-content {
    height: $main-height;
    .el-card {
      min-height: 100%;
    }
  }
  .space-content {
    height: $main-height;
    .el-card {
      min-height: 100%;
      .desc {
        margin-top: 50px;
      }
      .el-tree {
        margin: 100px 10px 100px 10px;
        min-width: 600px;
      }
      .node {
        border-bottom: 1px dashed rgb(240, 211, 211); /* 设置虚线，可以根据需要调整颜色和样式 */
        margin-bottom: 1px; /* 调整横线与上方内容的间距 */
        .el-text {
          font-size: 18px;
        }
      }
    }
  }
}
</style>
